package com.xjscrm.server.service.faqreply.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.mobile.collect.api.dto.MicaTransDto;
import com.uzai.mobile.collect.api.dto.msg.MicaFriendTalkMsg;
import com.uzai.mobile.collect.api.dto.trigger.talk.MicaTalkContentTextMsg;
import com.uzai.mobile.collect.api.enums.MicaMsgSource;
import com.uzai.mobile.collect.api.enums.MicaTalkMsgType;
import com.uzai.trace.TraceGenerate;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.grouppull.GroupPullData;
import com.xjscrm.common.vo.grouppull.GroupPullMsgData;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.server.biz.mq.producer.SendMsgProducer;
import com.xjscrm.server.common.util.DeviceTools;
import com.xjscrm.server.common.util.GroupTools;
import com.xjscrm.server.mapper.*;
import com.xjscrm.server.req.filterrule.CustomerBasicInfoExcludeFilterReq;
import com.xjscrm.server.req.filterrule.CustomerTimeExcludeFilterReq;
import com.xjscrm.server.req.filterrule.CustomerTagsExcludeFilterReq;
import com.xjscrm.server.service.customer.WwCustomerTagsService;
import com.xjscrm.server.service.faqreply.FaqReplyTalkFriendService;
import com.xjscrm.server.service.filterrule.CustomerCommonFilterService;
import com.xjscrm.server.service.grouppull.GroupPullDataService;
import com.xjscrm.server.service.msg.MsgSendService;
import com.xjscrm.server.vo.device.Device;
import com.xjscrm.server.vo.faqreply.KeywordGuideQuetion;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 处理智能回复服务接口
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class FaqReplayTalkFriendServiceImplCustomer implements FaqReplyTalkFriendService, CustomerCommonFilterService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SendMsgProducer sendMsgProducer;
    @Autowired
    private FaqReplyMapper faqReplyMapper;
    @Autowired
    private FaqReplyDeviceMapper faqReplyDeviceMapper;
    @Autowired
    private WwCustomerWhitelistMapper wwCustomerWhitelistMapper;
    @Autowired
    private WwDeviceMapper wwDeviceMapper;
    @Autowired
    private WwGroupMapper wwGroupMapper;
    @Autowired
    private WwGroupMemberMapper wwGroupMemberMapper;
    @Autowired
    private WwGroupTagsRelationMapper wwGroupTagsRelationMapper;
    @Autowired
    private WwCustomerTagsMapper wwCustomerTagsMapper;
    @Autowired
    private WwCustomerMapper wwCustomerMapper;
    @Autowired
    private FaqReplyQuestionMapper faqReplyQuestionMapper;
    @Autowired
    private MsgSendService msgSendService;
    @Autowired
    private GroupPullDataService groupPullDataService;
    @Autowired
    private WwCustomerBlacklistMapper wwCustomerBlacklistMapper;
    @Resource
    private WwCustomerTagsService wwCustomerTagsService;

    /**
     * 智能回复机器人发往客户的主动聊天消息
     *
     * @param micaTransDto 智能回复机器人发往客户的主动聊天消息
     * @return 实例对象
     */
    @Async("taskExecutorForXxJob")
    @TraceGenerate //注入消息id标签
    public void faqReplyByTalkFriend(MicaTransDto micaTransDto) {
        try {
            log.info("--监控系统日志--开始--");

            MicaFriendTalkMsg micaFriendTalkMsg = JSONObject.parseObject(micaTransDto.getData().toString(), MicaFriendTalkMsg.class);

            if (micaFriendTalkMsg == null) {
                return;
            }

            //默认黑名单不通过
            WwCustomerBlacklist wwCustomerBlacklist = wwCustomerBlacklistMapper.selectByWxid(micaTransDto.getMerId(), micaFriendTalkMsg.getSendWxId());
            if (wwCustomerBlacklist != null) { //在黑名单中
                log.info("黑名单会员wxid={}, merId={}", micaFriendTalkMsg.getSendWxId(), micaTransDto.getMerId());
                return;
            }

            if (StringUtils.isBlank(micaTransDto.getDeviceId())) {
                log.info("机器人wxid is null, merId={}", micaTransDto.getMerId());
                return;
            }

            //发送者微信id
            String sendWxId = micaFriendTalkMsg.getSendWxId();
            //发送者微信昵称
            String sendNickName = micaFriendTalkMsg.getSendNickName();
            //会话id
            String conversationId = micaFriendTalkMsg.getConversationId();

            if (StringUtils.isBlank(sendWxId) || StringUtils.isBlank(conversationId)) {
                return;
            }

            //查询该机器人的配置方案
            WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(micaTransDto.getDeviceId(), micaTransDto.getMerId());
            if (wwDevice == null) {
                return;
            }
            Device device = DeviceTools.transDevice(wwDevice);
            if (device == null) {
                return;
            }

            //只支持文本
            if (micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.TEXT.getCode().intValue()
//                    && micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.Picture.getCode().intValue()
            ) {
                return;
            }

            //查询该机器人配置的所有智能回复
            List<FaqReplyDevice> faqReplyDeviceList = faqReplyDeviceMapper.selectByDeviceUniqueId(device.getDeviceUniqueId(), device.getMerId());
            if (faqReplyDeviceList == null || faqReplyDeviceList.size() == 0) {
                log.info("未找到该机器人的智能回复方案，device={}, merId={}", micaTransDto.getDeviceId(), micaTransDto.getMerId());
                return;
            }

            //首先验证是否有引导语
            //id为deviceId + conversationId + seedWxid;
            String id = device.getId() + "_" + conversationId + "_" + sendWxId;
            String key = String.format(RedisCacheKeyEnum.FAQREPLY_KEYWORD_GUIDE.getKey(), id);
            Object object = redisTemplate.opsForValue().get(key);
            if (object != null) { //表示此时有引导语，故只处理引导语中的问题序号
                //引导语卡住时间，只接收文本消息
                if (micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.TEXT.getCode().intValue()) {
                    return;
                }

                //获取文本消息
                MicaTalkContentTextMsg textContent = micaFriendTalkMsg.getTextContent();
                if (textContent == null) {
                    return;
                }

                String text = textContent.getText();
                if (StringUtils.isBlank(text)) {
                    return;
                }

                //判断消息是否为数字，不是数字不处理
                if (!Tools.isNumeric(text)) {
                    return;
                }
                Integer orderNo = Integer.parseInt(text);

                List<KeywordGuideQuetion> keywordGuideQuetionList = JSONObject.parseArray(object.toString(), KeywordGuideQuetion.class);
                if (keywordGuideQuetionList == null) {
                    return;
                }
                if (orderNo <= 0 || orderNo > keywordGuideQuetionList.size()) {
                    return;
                }
                //获取用户属于的引导语问题编号
                KeywordGuideQuetion keywordGuideQuetion = keywordGuideQuetionList.get(orderNo - 1);
                if (keywordGuideQuetion != null) {
                    //回复方式(0-按照顺序全部回复;1-随机回复一条)
                    Integer type = Tools.getInteger(keywordGuideQuetion.getType());
                    List<GroupPullData> groupPullDataList_question = JSONObject.parseArray(keywordGuideQuetion.getMsgDatas(), GroupPullData.class);
                    List<GroupPullData> groupPullDataList = new ArrayList<>();
                    if (groupPullDataList_question != null) {
                        if (type.intValue() == 1) { //随机一条
                            int rateMin = 0;
                            int rateMax = groupPullDataList_question.size() - 1;
                            //获取最小和最大时间的随机数（分数）
                            int rateRandom = (int) (Math.random() * (rateMax - rateMin + 1) + rateMin);
                            groupPullDataList.add(groupPullDataList_question.get(rateRandom));
                        } else {
                            groupPullDataList = groupPullDataList_question;
                        }

                        //封装拉群数据
                        WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), sendWxId);
                        if (wwCustomer == null) {
                            wwCustomer = new WwCustomer();
                            wwCustomer.setWxid(sendWxId);
                            wwCustomer.setGender(0); //默认未知性别
                        }

                        List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(device.getMerId(), groupPullDataList, wwCustomer, device);
                        if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                            //智能回复拉群
                            msgSendService.groupPullMsgSendByFaqReplay(device.getMerId(), device, conversationId, sendNickName, groupPullMsgDataList, 5, keywordGuideQuetion.getReplyId(), false, null, MicaMsgSource.FAQ_REPLY.getCode(), micaFriendTalkMsg.getGroup());
                            //删除引导语
                            redisTemplate.delete(key);
                        }
                    }
                }
            } else {
                //条件验证
                for (FaqReplyDevice faqReplyDevice : faqReplyDeviceList) {
                    //验证条件
                    FaqReply faqReply = faqReplyMapper.selectById(faqReplyDevice.getTaskId());
                    if (faqReply != null) {
                        //验证条件
                        boolean result = verifyParaByTalkFriend(faqReply, micaFriendTalkMsg, device);
                        if (!result) {
                            continue;
                        }
                        //文本回复
                        if (micaFriendTalkMsg.getMsgType().intValue() == MicaTalkMsgType.TEXT.getCode().intValue()) {
                            faqReplyByTalkFriend_textMsg(faqReply, micaFriendTalkMsg, device);
                        } else if (micaFriendTalkMsg.getMsgType().intValue() == MicaTalkMsgType.Picture.getCode().intValue()) {//图片回复
                            // TODO: 2024/3/28
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }finally {
            log.info("--监控系统日志--结束--");
        }
    }

    /**
     * 处理文本回复
     *
     * @param micaFriendTalkMsg 聊天消息
     * @return 实例对象
     */
    private void faqReplyByTalkFriend_textMsg(FaqReply faqReply, MicaFriendTalkMsg micaFriendTalkMsg, Device device) {
        try {
            //发送者微信id
            String sendWxId = micaFriendTalkMsg.getSendWxId();
            //发送者微信昵称
            String sendNickName = micaFriendTalkMsg.getSendNickName();
            //会话id
            String conversationId = micaFriendTalkMsg.getConversationId();

            //封装拉群数据
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getDeviceUniqueId(), sendWxId);
            if (wwCustomer == null) {
                wwCustomer = new WwCustomer();
                wwCustomer.setWxid(sendWxId);
                wwCustomer.setGender(0); //默认未知性别
            }

            //匹配关键词智能回复
            List<FaqReplyQuestion> faqReplyQuestionList = textMsgByTalkFriend(faqReply, micaFriendTalkMsg, device);
            if (faqReplyQuestionList != null && faqReplyQuestionList.size() > 0) { //找到了关键词触发问题
                if (faqReplyQuestionList.size() == 1) {//单个问题
                    FaqReplyQuestion faqReplyQuestion = faqReplyQuestionList.get(0);
                    //回复方式(0-按照顺序全部回复;1-随机回复一条)
                    Integer type = Tools.getInteger(faqReplyQuestion.getType());
                    //封装发送的消息
                    List<GroupPullData> groupPullDataList = new ArrayList<>();
                    List<GroupPullData> groupPullDataList_question = JSONObject.parseArray(faqReplyQuestion.getMsgDatas(), GroupPullData.class);
                    if (groupPullDataList_question != null && groupPullDataList_question.size() > 0) {
                        if (type.intValue() == 1) { //随机一条
                            int rateMax = groupPullDataList_question.size() - 1;
                            int rateMin = 0;
                            //获取最小和最大时间的随机数（分数）
                            int rateRandom = (int) (Math.random() * (rateMax - rateMin + 1) + rateMin);
                            groupPullDataList.add(groupPullDataList_question.get(rateRandom));
                        } else {
                            groupPullDataList = groupPullDataList_question;
                        }
                        if (groupPullDataList != null && groupPullDataList.size() > 0) {//有消息才发送
                            //判断回复是否带问题
                            if (Tools.getInteger(faqReply.getKeywordReplyQuest()).intValue() == 1) {
                                GroupPullData groupPullData = new GroupPullData();
                                groupPullData.setMsgType(MicaTalkMsgType.TEXT.getCode());
                                groupPullData.setContent(faqReplyQuestion.getQuestion());
                                groupPullDataList.add(0, groupPullData); //将问题添加到回复语的第一个位置
                            }

                            //回复消息是否@对方
                            List<String> atWxidList = null;
                            if (Tools.getInteger(faqReply.getKeywordReplyAtSender()).intValue() == 1) {
                                atWxidList = new ArrayList<>();
                                atWxidList.add(sendWxId);
                            }

                            //缓存记录此对象同一个问题发送时间
                            if (Tools.getInteger(faqReply.getKeywordTiggerSame()).intValue() == 1) {
                                //id为deviceId + faqReplyId + conversationId + seedWxid + questId;
                                String id = device.getDeviceId() + "_" + faqReply.getId() + "_" + conversationId + "_" + sendWxId + "_" + faqReplyQuestion.getId();
                                String key = String.format(RedisCacheKeyEnum.FAQREPLY_KEYWORD_TIGGER_SAME_QUESTION.getKey(), id);
                                Object object = redisTemplate.opsForValue().get(key);
                                if (object == null) { //表示此问题还未发送，可以发送
                                    List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(device.getMerId(), groupPullDataList, wwCustomer, device);
                                    if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                                        //智能回复拉群
                                        msgSendService.groupPullMsgSendByFaqReplay(device.getMerId(), device, conversationId, sendNickName, groupPullMsgDataList, 5, faqReplyQuestion.getReplyId(), false, atWxidList, MicaMsgSource.FAQ_REPLY.getCode(), micaFriendTalkMsg.getGroup());
                                    }
                                    //同时写入缓存
                                    Integer keywordTiggerSameReplyTime = Tools.getInteger(faqReply.getKeywordTiggerSameReplyTime());
                                    redisTemplate.opsForValue().set(key, faqReplyQuestion.getId(), keywordTiggerSameReplyTime, TimeUnit.MINUTES);
                                }
                            } else {
                                //发送消息
                                List<GroupPullMsgData> groupPullMsgDataList = groupPullDataService.handGroupPullData(device.getMerId(), groupPullDataList, wwCustomer, device);
                                if (groupPullMsgDataList != null && groupPullMsgDataList.size() > 0) {
                                    //智能回复拉群
                                    msgSendService.groupPullMsgSendByFaqReplay(device.getMerId(), device, conversationId, sendNickName, groupPullMsgDataList, 5, faqReplyQuestion.getReplyId(), false, atWxidList, MicaMsgSource.FAQ_REPLY.getCode(), micaFriendTalkMsg.getGroup());
                                }
                            }
                        }
                    }
                } else {//多个问题，需要触发引导语
                    //引导语缓存对象
                    List<KeywordGuideQuetion> keywordGuideQuetionList = new ArrayList<>();
                    String keywordGuide = Tools.getStr(faqReply.getKeywordGuide());
                    for (int i = 0; i < faqReplyQuestionList.size(); i++) {
                        FaqReplyQuestion faqReplyQuestion = faqReplyQuestionList.get(i);
                        KeywordGuideQuetion keywordGuideQuetion = new KeywordGuideQuetion();
                        BeanUtils.copyProperties(faqReplyQuestion, keywordGuideQuetion);
                        int orderNo = i + 1; //问题序号从1开始
                        keywordGuide = keywordGuide + "\n"
                                + orderNo + "、" + keywordGuideQuetion.getQuestion() + "\n";
                        keywordGuideQuetionList.add(keywordGuideQuetion);
                    }

                    //发送引导语
                    List<MsgData> msgDataList = new ArrayList<>();
                    MsgData msgData_keywordGuide = new MsgData();
                    msgData_keywordGuide.setMsgType(MicaTalkMsgType.TEXT.getCode());
                    msgData_keywordGuide.setContent(keywordGuide);
                    msgDataList.add(msgData_keywordGuide);

                    //回复消息是否@对方
                    List<String> atWxidList = null;
                    if (Tools.getInteger(faqReply.getKeywordReplyAtSender()).intValue() == 1) {
                        atWxidList = new ArrayList<>();
                        atWxidList.add(sendWxId);
                    }
                    //发送消息
                    msgSendService.msgSend(device, sendWxId, sendNickName, msgDataList, false, atWxidList, MicaMsgSource.FAQ_REPLY.getCode(), micaFriendTalkMsg.getGroup());

                    //同时写入引导语缓存，卡一分钟不回复
                    //id为deviceId + conversationId + seedWxid;
                    String id = device.getId() + "_" + conversationId + "_" + sendWxId;
                    String key = String.format(RedisCacheKeyEnum.FAQREPLY_KEYWORD_GUIDE.getKey(), id);
                    redisTemplate.opsForValue().set(key, JSONObject.toJSONString(keywordGuideQuetionList), 1, TimeUnit.MINUTES);
                }
            } else {//未匹配到关键词回复，需要触发默认回复
                // TODO: 2024/3/28
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }


    /**
     * 验证消息智能回复
     *
     * @param micaFriendTalkMsg 聊天消息
     * @return 实例对象
     */
    private boolean verifyParaByTalkFriend(FaqReply faqReply, MicaFriendTalkMsg micaFriendTalkMsg, Device device) {

        //发送者
        String sendWxId = micaFriendTalkMsg.getSendWxId();

        //应用时间段
        String timeStart = faqReply.getTimeStart();
        String timeEnd = faqReply.getTimeEnd();
        //指定日期
        String useDayStart = faqReply.getUseDayStart();
        String useDayEnd = faqReply.getUseDayEnd();

        //使用类型（0-长期使用;1-指定时间生效）
        Integer useType = Tools.getInteger(faqReply.getUseType());
        if (useType.intValue() == 0) { //长期应用,配置的指定时间不起左右
            useDayStart = null;
            useDayEnd = null;
        }
        //验证日期和时间是否都符合
        boolean timeResult = Tools.isWithinDateAndTimeInterval(LocalDateTime.now(), useDayStart, useDayEnd, timeStart, timeEnd);
        if (!timeResult) {//不在区间内，跳出次配置方案
            return false;
        }

        //验证排除白名单对象
        Integer excludeWhitelist = Tools.getInteger(faqReply.getExcludeWhitelist());
        if (excludeWhitelist.intValue() == 1) {//开启不处理白名单消息
            //查询是否在白名单当中,在白名单中，则跳过不处理
            WwCustomerWhitelist wwCustomerWhitelist = wwCustomerWhitelistMapper.selectByWxid(device.getMerId(), micaFriendTalkMsg.getSendWxId());
            if (wwCustomerWhitelist != null) {
                return false;
            }
        }

        //验证是否是其他机器人发的消息
        Integer excludeRobot = Tools.getInteger(faqReply.getExcludeRobot());
        if (excludeRobot.intValue() == 1) {//开启不处理其他机器人消息
            if (!device.getDeviceId().equals(sendWxId)) {//不是机器人自己
                //是否是机器人
                WwDevice wwDevice = wwDeviceMapper.queryByDeviceId(sendWxId, faqReply.getMerId());
                if (wwDevice != null) {//是其他机器人发的消息
                    return false;
                }
            }
        }

        //是否是群聊消息
        if (micaFriendTalkMsg.getGroup()) {
            //群wxid
            String groupWxid = Tools.getStr(micaFriendTalkMsg.getConversationId());
            String groupName = Tools.getStr(micaFriendTalkMsg.getConversationName());

            //获取群信息
            WwGroup wwGroup = wwGroupMapper.queryByDeviceUniqueIdAndGroupWxid(device.getId(), groupWxid);
            if (wwGroup == null) {
                return false;
            }

            //查询此机器人是否在群内成员
//            WwGroupMember wwGroupMember = wwGroupMemberMapper.selectByGroupWxidAndWxid(wwGroup.getMerId(), groupWxid, wwGroup.getDeviceId());
//            if(wwGroupMember == null){
//                return false;
//            }

            //是否开启群聊开关
            Integer groupSwitch = Tools.getInteger(faqReply.getGroupSwitch());
            if (groupSwitch.intValue() == 0) { //不开启群聊消息，直接不通过
                return false;
            }

            //群类型(0-全部客户；1-部分客户)
            Integer groupType = Tools.getInteger(faqReply.getGroupType());
            if (groupType.intValue() == 1) { //部分客户，则需要验证条件

                //群名关键词选项(0-含任意关键词；1-含所有关键词)
                Integer groupNameKeywordOpt = faqReply.getGroupNameKeywordOpt();
                if (groupNameKeywordOpt != null) {
                    //群名关键词列表
                    List<String> groupNameKeywordList = JSONObject.parseArray(faqReply.getGroupNameKeywords(), String.class);
                    if (groupNameKeywordList == null || groupNameKeywordList.size() == 0) { //没有找到，则不回复
                        return false;
                    }

                    if (groupNameKeywordOpt.intValue() == 0) { //满足任意一个
                        boolean groupNameKeywordFlag = false;
                        for (String keyword : groupNameKeywordList) {
                            if (groupName.contains(keyword)) {//找到一个符合的，就返回通过
                                groupNameKeywordFlag = true;
                            }
                        }
                        if (!groupNameKeywordFlag) {
                            return false;
                        }
                    } else {//满足所有触发
                        for (String keyword : groupNameKeywordList) {
                            if (!groupName.contains(keyword)) {//找到一个不符合的，就返回不通过
                                return false;
                            }
                        }
                    }
                }

                //群标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
                Integer groupTagOpt = faqReply.getGroupTagOpt();
                if (groupTagOpt != null) {

                    //封装此群已打的标签
                    List<WwGroupTagsRelation> wwGroupTagsRelationList = wwGroupTagsRelationMapper.selectByDeviceIdAndGroupWxid(device.getMerId(), device.getDeviceId(), groupWxid);
                    List<Long> wwGroupTagedList = new ArrayList<>();
                    if (wwGroupTagsRelationList != null && wwGroupTagsRelationList.size() > 0) {
                        for (WwGroupTagsRelation wwGroupTagsRelation : wwGroupTagsRelationList) {
                            wwGroupTagedList.add(wwGroupTagsRelation.getTagId());
                        }
                    }

                    //2-未打任何标签
                    if (groupTagOpt.intValue() == 2) {
                        if (wwGroupTagedList.size() > 0) {
                            return false;
                        }
                    } else {
                        //标签列表
                        List<Long> groupTagList = JSONObject.parseArray(faqReply.getGroupTags(), Long.class);
                        if (groupTagList == null || groupTagList.size() == 0) { //没有找到，则不回复
                            return false;
                        }
                        if (groupTagOpt.intValue() == 0) { //满足任意一个
                            boolean tagFlag = false;
                            for (Long groupTag : groupTagList) {
                                if (wwGroupTagedList.contains(groupTag)) {//找到一个符合的，就返回通过
                                    tagFlag = true;
                                    break;
                                }
                            }
                            if (!tagFlag) {
                                return false;
                            }
                        } else if (groupTagOpt.intValue() == 1) {//满足所有触发
                            if (!wwGroupTagedList.containsAll(groupTagList)) {
                                return false;
                            }
                        }
                    }
                }

                //群成员角色列表(0-群主；1-管理员；2-普通成员)
                String groupMemberIdentitys = faqReply.getGroupMemberIdentitys();
                List<Integer> groupMemberIdentityList = JSONObject.parseArray(groupMemberIdentitys, Integer.class);
                if (groupMemberIdentityList != null && groupMemberIdentityList.size() > 0) {
                    boolean identityFlag = GroupTools.verifyIdentity(wwGroup, groupMemberIdentityList, device.getDeviceId());
                    if (!identityFlag) {
                        return false;
                    }
                }

                //验证群人数
                Integer groupMemberTotalMin = faqReply.getGroupMemberTotalMin();
                Integer groupMemberTotalMax = faqReply.getGroupMemberTotalMax();
                if (groupMemberTotalMin != null
                        && groupMemberTotalMax != null
                        && groupMemberTotalMin.intValue() <= groupMemberTotalMin.intValue()
                ) {
                    //在群人数
                    String groupMemberCountKey = String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), groupWxid);
                    Integer groupMemberCount = (Integer) redisTemplate.opsForValue().get(groupMemberCountKey);
                    Integer memberTotal = Tools.getInteger(groupMemberCount);
                    if (memberTotal.intValue() < groupMemberTotalMin.intValue()
                            || memberTotal.intValue() > groupMemberTotalMax.intValue()
                    ) {
                        return false;
                    }
                }

                //验证建群时间
                String groupCreateDayStart = faqReply.getGroupCreateDayStart();
                String groupCreateDayEnd = faqReply.getGroupCreateDayEnd();
                if (StringUtils.isNotBlank(groupCreateDayStart)
                        && StringUtils.isNotBlank(groupCreateDayEnd)
                ) {
                    Integer groupCreateTime = wwGroup.getGroupCreateTime();
                    if (groupCreateTime == null) {//如果没有建群时间，则不通过
                        return false;
                    }
                    //判断旧发送时间是否在允许区间内
                    Instant instant_groupCreateTime = Instant.ofEpochMilli(groupCreateTime * 1000L);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
                    boolean withinTimeInterval_groupCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(groupCreateDayStart), LocalDate.parse(groupCreateDayEnd));
                    if (!withinTimeInterval_groupCreateTime) {
                        return false;
                    }
                }
            }
        } else { //私聊消息
            //获取客户信息
            WwCustomer wwCustomer = wwCustomerMapper.queryByDeviceUniqueIdAndWxid(device.getId(), sendWxId);
            if (wwCustomer == null) {
                return false;
            }

            //是否开启群聊开关
            Integer customerSwitch = Tools.getInteger(faqReply.getCustomerSwitch());
            if (customerSwitch.intValue() == 0) { //不开启客户消息，直接不通过
                return false;
            }

            //客户类型(0-全部客户；1-部分客户)
            Integer customerType = Tools.getInteger(faqReply.getCustomerType());
            if (customerType.intValue() == 1) { //部分客户，则需要验证条件
                //获取客户已打的标签
                List<Long> wwCustomerTagedList = wwCustomerTagsService.getTagIds(wwCustomer.getMerId(), wwCustomer.getId());
                //客户企业标签选项(0-含任意标签；1-含所有标签；2-未打任何标签)
                Integer customerEnterpriseTagOpt = faqReply.getCustomerEnterpriseTagOpt();
                if (customerEnterpriseTagOpt != null) {

                    //2-未打任何标签
                    if (customerEnterpriseTagOpt.intValue() == 2) {
                        if (wwCustomerTagedList.size() > 0) {
                            return false;
                        }
                    } else {
                        //标签列表
                        List<Long> customerEnterpriseTagList = JSONObject.parseArray(faqReply.getCustomerEnterpriseTags(), Long.class);
                        if (customerEnterpriseTagList == null || customerEnterpriseTagList.size() == 0) { //没有找到，则不回复
                            return false;
                        }
                        if (customerEnterpriseTagOpt.intValue() == 0) { //满足任意一个
                            boolean tagFlag = false;
                            for (Long customerEnterpriseTag : customerEnterpriseTagList) {
                                if (wwCustomerTagedList.contains(customerEnterpriseTag)) {//找到一个符合的，就返回通过
                                    tagFlag = true;
                                    break;
                                }
                            }
                            if (!tagFlag) {
                                return false;
                            }
                        } else if (customerEnterpriseTagOpt.intValue() == 1) {//满足所有触发
                            if (!wwCustomerTagedList.containsAll(customerEnterpriseTagList)) {
                                return false;
                            }
                        }
                    }
                }

                //加好友时间
                String customerCreateDayStart = faqReply.getCustomerCreateDayStart();
                String customerCreateDayEnd = faqReply.getCustomerCreateDayEnd();
                if (StringUtils.isNotBlank(customerCreateDayStart)
                        && StringUtils.isNotBlank(customerCreateDayEnd)
                ) {
                    Integer customerCreateTime = wwCustomer.getCreateTime();
                    if (customerCreateTime == null) {//如果没有添加好友时间，则不通过
                        return false;
                    }
                    //判断旧发送时间是否在允许区间内
                    Instant instant_groupCreateTime = Instant.ofEpochMilli(customerCreateTime * 1000L);
                    LocalDateTime localDateTime = LocalDateTime.ofInstant(instant_groupCreateTime, ZoneId.systemDefault());
                    boolean withinTimeInterval_customerCreateTime = Tools.isWithinDateInterval(localDateTime, LocalDate.parse(customerCreateDayStart), LocalDate.parse(customerCreateDayEnd));
                    if (!withinTimeInterval_customerCreateTime) {
                        return false;
                    }
                }

                //客户备注选项(0-无备注；1-有备注)
                Integer customerRemarkOpt = faqReply.getCustomerRemarkOpt();
                if (customerRemarkOpt != null) {
                    if (customerRemarkOpt.intValue() == 0) {//无备注
                        if (StringUtils.isNotBlank(wwCustomer.getRemark())) {
                            return false;
                        }
                    } else if (customerRemarkOpt.intValue() == 1) { //有备注
                        if (StringUtils.isBlank(wwCustomer.getRemark())) {
                            return false;
                        }
                    }
                }

                //性别(0-未知；1-男；2-女)
                Integer customerGenders = faqReply.getCustomerGenders();
                if (customerGenders != null) {
                    //验证客户性别是否跟配置的符合
                    if (customerGenders.intValue() != Tools.getInteger(wwCustomer.getGender()).intValue()) {
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //封装文本消息智能回复
    private List<FaqReplyQuestion> textMsgByTalkFriend(FaqReply faqReply, MicaFriendTalkMsg micaFriendTalkMsg, Device device) {
        //封装触发的问题
        List<FaqReplyQuestion> faqReplyQuestionList_tragger = new ArrayList<>();

        if (micaFriendTalkMsg.getMsgType().intValue() != MicaTalkMsgType.TEXT.getCode()) {
            return faqReplyQuestionList_tragger;
        }

        //获取文本消息
        MicaTalkContentTextMsg textContent = micaFriendTalkMsg.getTextContent();
        if (textContent == null) {
            return faqReplyQuestionList_tragger;
        }

        String text = textContent.getText();
        if (StringUtils.isBlank(text)) {
            return faqReplyQuestionList_tragger;
        }

        //自己可触发关键词
        Integer keywordTiggerMyself = Tools.getInteger(faqReply.getKeywordTiggerMyself());
        if (keywordTiggerMyself.intValue() != 1) {//不开启自己可触发关键词，则不触发
            return faqReplyQuestionList_tragger;
        }

        //群消息验证是否开启@自己回复
        if (micaFriendTalkMsg.getGroup()) {
            Integer keywordTriggerAtMe = Tools.getInteger(faqReply.getKeywordTriggerAtMe());
            if (keywordTriggerAtMe.intValue() == 1) {//开启，则需要验证是否@自己
                if (micaFriendTalkMsg.getAtMe() == null || !micaFriendTalkMsg.getAtMe()) {//不是@自己
                    return faqReplyQuestionList_tragger;
                }
            }
        }

        //查询该智能回复所有开启的问题
        List<FaqReplyQuestion> faqReplyQuestionList = faqReplyQuestionMapper.selectByReplyId(faqReply.getId(), faqReply.getMerId(), 1);
        if (faqReplyQuestionList != null && faqReplyQuestionList.size() > 0) {
            for (FaqReplyQuestion faqReplyQuestion : faqReplyQuestionList) {
                //精准关键词列表
                List<String> keywordList = JSONObject.parseArray(faqReplyQuestion.getKeywords(), String.class);
                if (keywordList != null && keywordList.size() > 0) {
                    //判断是否触发精准关键词
                    if (keywordList.contains(text)) {
                        //封装倒触发的问题列表中
                        textMsgByTalkFriendTraggerQuestion(faqReplyQuestionList_tragger, faqReplyQuestion);
                        continue;
                    }
                }

                //模糊关键词列表
                List<String> fuzzyKeywordList = JSONObject.parseArray(faqReplyQuestion.getFuzzyKeywords(), String.class);
                if (fuzzyKeywordList != null && fuzzyKeywordList.size() > 0) {
                    //判断是否模糊查询
                    for (String fuzzyKeyword : fuzzyKeywordList) {
                        if (text.contains(fuzzyKeyword)) {
                            //封装倒触发的问题列表中
                            textMsgByTalkFriendTraggerQuestion(faqReplyQuestionList_tragger, faqReplyQuestion);
                            continue;
                        }
                    }
                }
            }
        }

        //去重复
        faqReplyQuestionList_tragger = faqReplyQuestionList_tragger.stream().distinct().collect(Collectors.toList());

        return faqReplyQuestionList_tragger;
    }

    /**
     * 排查列表中的问题权重，如果大于则刷新列表中的问题，如果等于，在添加，如果小于，在丢弃
     *
     * @param faqReplyQuestionList_tragger
     * @param faqReplyQuestion
     * @return java.util.List<com.xjscrm.common.vo.msg.MsgData>
     * @author lucher
     * @date 2024/3/28 11:22
     */
    private List<FaqReplyQuestion> textMsgByTalkFriendTraggerQuestion(List<FaqReplyQuestion> faqReplyQuestionList_tragger, FaqReplyQuestion faqReplyQuestion) {

        if (faqReplyQuestionList_tragger == null) {
            faqReplyQuestionList_tragger = new ArrayList<>();
        }

        if (faqReplyQuestionList_tragger.size() == 0) {
            faqReplyQuestionList_tragger.add(faqReplyQuestion);
        } else {
            //新来问题的权重
            Integer priority = Tools.getInteger(faqReplyQuestion.getPriority());
            //列表中的权重（取第一个元素出来就行，因为整个列表对象的权重都是相同的）
            FaqReplyQuestion faqReplyQuestion_tragger0 = faqReplyQuestionList_tragger.get(0);
            Integer priority_tragger0 = Tools.getInteger(faqReplyQuestion_tragger0.getPriority());
            //如果新权重大于列表权重，则刷新列表中的问题，如果等于，在添加，如果小于，则丢弃
            if (priority.intValue() > priority_tragger0.intValue()) {
                faqReplyQuestionList_tragger.clear();
                faqReplyQuestionList_tragger.add(faqReplyQuestion);
            } else if (priority.intValue() == priority_tragger0.intValue()) {
                faqReplyQuestionList_tragger.add(faqReplyQuestion);
            }
        }

        return faqReplyQuestionList_tragger;
    }


}
